document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const startBtn = document.getElementById('startBtn');
    const pauseBtn = document.getElementById('pauseBtn');
    const currentScoreElement = document.getElementById('currentScore');
    const leaderboardList = document.getElementById('leaderboardList');
    const difficultySelect = document.getElementById('difficultySelect');
    const mapSizeSelect = document.getElementById('mapSizeSelect');

    // 游戏配置
    const difficulties = {
        easy: { initialSpeed: 250, speedIncrease: 1 },
        normal: { initialSpeed: 200, speedIncrease: 2 },
        hard: { initialSpeed: 120, speedIncrease: 4 },
        hell: { initialSpeed: 80, speedIncrease: 5 }
    };

    const mapSizes = {
        small: { width: 400, height: 300 },
        medium: { width: 600, height: 400 },
        large: { width: 800, height: 500 },
        huge: { width: 1000, height: 600 }
    };

    const gridSize = 20;
    let gameLoop = null;
    let score = 0;
    let speed = difficulties.normal.initialSpeed;
    let speedIncrease = difficulties.normal.speedIncrease;
    let isPaused = false;

    // 更新画布大小
    function updateCanvasSize() {
        const size = mapSizes[mapSizeSelect.value];
        canvas.width = size.width;
        canvas.height = size.height;
    }

    // 更新游戏难度
    function updateDifficulty() {
        const difficulty = difficulties[difficultySelect.value];
        speed = difficulty.initialSpeed;
        speedIncrease = difficulty.speedIncrease;
    }

    // 蛇的初始状态
    let snake = {
        body: [
            { x: 7, y: 10 },
            { x: 6, y: 10 },
            { x: 5, y: 10 }
        ],
        direction: 'right'
    };

    // 食物和陷阱位置
    let food = generateFood();
    let traps = [];

    // 生成陷阱
    function generateTraps() {
        const trapCount = Math.floor(Math.random() * 3) + 1; // 1-3个陷阱
        traps = [];
        for (let i = 0; i < trapCount; i++) {
            let trap;
            do {
                trap = {
                    x: Math.floor(Math.random() * (canvas.width / gridSize)),
                    y: Math.floor(Math.random() * (canvas.height / gridSize))
                };
            } while (isOverlapping(trap));
            traps.push(trap);
        }
    }

    // 检查位置是否重叠
    function isOverlapping(pos) {
        // 检查是否与食物重叠
        if (pos.x === food.x && pos.y === food.y) return true;
        // 检查是否与其他陷阱重叠
        return traps.some(trap => trap.x === pos.x && trap.y === pos.y);
    }

    // 触摸控制相关变量
    let touchStartX = 0;
    let touchStartY = 0;

    // 生成食物
    function generateFood() {
        const x = Math.floor(Math.random() * (canvas.width / gridSize));
        const y = Math.floor(Math.random() * (canvas.height / gridSize));
        return { x, y };
    }

    // 绘制游戏场景
    function draw() {
        // 清空画布
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制蛇
        ctx.fillStyle = '#4CAF50';
        snake.body.forEach((segment, index) => {
            if (index === 0) {
                // 蛇头
                ctx.fillStyle = '#388E3C';
            } else {
                ctx.fillStyle = '#4CAF50';
            }
            ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
        });

        // 绘制食物
        ctx.fillStyle = '#F44336';
        ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 1, gridSize - 1);

        // 绘制陷阱
        ctx.fillStyle = '#9C27B0';
        traps.forEach(trap => {
            ctx.fillRect(trap.x * gridSize, trap.y * gridSize, gridSize - 1, gridSize - 1);
        });
    }

    // 移动蛇
    function moveSnake() {
        const head = { ...snake.body[0] };

        switch (snake.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }

        // 检查碰撞
        if (checkCollision(head) || checkTrapCollision(head)) {
            gameOver();
            return;
        }

        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            food = generateFood();
            score += 10;
            speed = Math.max(50, speed - speedIncrease);
            currentScoreElement.textContent = score;
            updateTraps();
        } else {
            snake.body.pop();
        }

        snake.body.unshift(head);
    }

    // 碰撞检测
    function checkCollision(head) {
        // 检查墙壁碰撞
        if (head.x < 0 || head.x >= canvas.width / gridSize ||
            head.y < 0 || head.y >= canvas.height / gridSize) {
            return true;
        }

        // 检查自身碰撞
        return snake.body.some(segment => segment.x === head.x && segment.y === head.y);
    }

    // 检查陷阱碰撞
    function checkTrapCollision(head) {
        return traps.some(trap => trap.x === head.x && trap.y === head.y);
    }

    // 更新陷阱位置
    function updateTraps() {
        if (score > 0 && score % 50 === 0) { // 每得50分更新陷阱位置
            generateTraps();
        }
        // 检查墙壁碰撞
        if (head.x < 0 || head.x >= canvas.width / gridSize ||
            head.y < 0 || head.y >= canvas.height / gridSize) {
            return true;
        }

        // 检查自身碰撞
        return snake.body.some(segment => segment.x === head.x && segment.y === head.y);
    }

    // 游戏结束
    function gameOver() {
        clearInterval(gameLoop);
        updateLeaderboard(score);
        alert(`游戏结束！得分：${score}`);
        startBtn.textContent = '重新开始';
        startBtn.disabled = false;
        pauseBtn.disabled = true;
    }

    // 更新排行榜
    function updateLeaderboard(newScore) {
        let scores = JSON.parse(localStorage.getItem('snakeGameScores') || '[]');
        scores.push(newScore);
        scores.sort((a, b) => b - a);
        scores = scores.slice(0, 5); // 只保留前5名
        localStorage.setItem('snakeGameScores', JSON.stringify(scores));
        displayLeaderboard();
    }

    // 显示排行榜
    function displayLeaderboard() {
        const scores = JSON.parse(localStorage.getItem('snakeGameScores') || '[]');
        leaderboardList.innerHTML = scores
            .map((score, index) => `<li class="leaderboard-item">${index + 1}. ${score}分</li>`)
            .join('');
    }

    // 初始化游戏
    function initGame() {
        updateCanvasSize();
        updateDifficulty();
        snake = {
            body: [
                { x: 7, y: 10 },
                { x: 6, y: 10 },
                { x: 5, y: 10 }
            ],
            direction: 'right'
        };
        food = generateFood();
        score = 0;
        currentScoreElement.textContent = '0';
        isPaused = false;
        pauseBtn.textContent = '暂停';
    }

    // 开始游戏
    function startGame() {
        if (gameLoop) {
            clearInterval(gameLoop);
        }
        initGame();
        generateTraps();
        gameLoop = setInterval(() => {
            if (!isPaused) {
                moveSnake();
                draw();
            }
        }, speed);
        startBtn.disabled = true;
        pauseBtn.disabled = false;
    }

    // 事件监听
    startBtn.addEventListener('click', startGame);

    pauseBtn.addEventListener('click', () => {
        isPaused = !isPaused;
        pauseBtn.textContent = isPaused ? '继续' : '暂停';
    });

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        if (isPaused) return;

        switch (e.key) {
            case 'ArrowUp':
                if (snake.direction !== 'down') snake.direction = 'up';
                break;
            case 'ArrowDown':
                if (snake.direction !== 'up') snake.direction = 'down';
                break;
            case 'ArrowLeft':
                if (snake.direction !== 'right') snake.direction = 'left';
                break;
            case 'ArrowRight':
                if (snake.direction !== 'left') snake.direction = 'right';
                break;
        }
    });

    // 触摸控制
    canvas.addEventListener('touchstart', (e) => {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
    });

    canvas.addEventListener('touchmove', (e) => {
        if (isPaused) return;
        e.preventDefault();

        const touchEndX = e.touches[0].clientX;
        const touchEndY = e.touches[0].clientY;
        const dx = touchEndX - touchStartX;
        const dy = touchEndY - touchStartY;

        if (Math.abs(dx) > Math.abs(dy)) {
            // 水平移动
            if (dx > 0 && snake.direction !== 'left') {
                snake.direction = 'right';
            } else if (dx < 0 && snake.direction !== 'right') {
                snake.direction = 'left';
            }
        } else {
            // 垂直移动
            if (dy > 0 && snake.direction !== 'up') {
                snake.direction = 'down';
            } else if (dy < 0 && snake.direction !== 'down') {
                snake.direction = 'up';
            }
        }
    });

    // 初始化排行榜
    displayLeaderboard();

    // 初始化画布大小
    updateCanvasSize();

    // 初始绘制游戏场景
    draw();
});